/**
 * Copyright(c) by JNet Smartware Group.
 * All rights reserved. Not distribution or redistribution without
 * any permission of JNet Smartware Group.
 * 
 * @author thong
 * 2010/08/09
 * Program: SWTRoomSearch.java
 */
package vn.smartware.co.client.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.TableTree;
import org.eclipse.swt.custom.TableTreeItem;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import vn.smartware.co.commons.Const;
import vn.smartware.co.commons.SWTUtils;
import vn.smartware.co.dto.MstRoomDTO;
import vn.smartware.co.dto.MstRoomPriceDTO;
import vn.smartware.co.framework.common.BaseConstant;
import vn.smartware.co.framework.exception.ClientException;
import vn.smartware.co.framework.exception.FatalException;
import vn.smartware.co.framework.form.CommonSearchForm;
import vn.smartware.co.framework.plugin.LangResources;
import vn.smartware.co.framework.swt.base.JNetShell;
import vn.smartware.co.framework.utils.MsgBoxUtils;
import vn.smartware.co.java.net.commons.Utils;

/**
 * SWTRoomSearch
 * @author thongld
 */
@SuppressWarnings({"rawtypes","deprecation"})
public class SWTRoomSearch extends JNetShell {

	private static Log log = LogFactory.getLog(SWTRoomSearch.class);
	
	private TableTree tableTree;

	private Combo cmbType;
	
	private Combo cmbRoomStatus;

	private Text txtSearchName;

	private Button btnSearch;

	private Text txtNoEnd;

	private Text txtNoStart;

	private Group grpSearch;

	private Button btnClose;

	private Button btnClear;

	private Table tblInfo;

	private CLabel clblMessage;

	private Button btnSelect;

	private static final int SIZE_X = 670;

	private static final int SIZE_Y = 600;

	private static final int TBL_ROW_COUNT = 16;
	
	/**
	 * Constructor
	 * @param parent
	 * @param form 
	 */
	public SWTRoomSearch(Shell parent) {
		super(parent, LangResources.getText("SWTRoomSearch.shell"), new Point(SIZE_X, SIZE_Y));
	}

	/* (non-Javadoc)
	 * @see vn.smartware.co.framework.swt.base.JNetShell#displaySearchCriteria()
	 */
	@Override
	protected void displaySearchCriteria() {
		if (!Utils.isNullEmpty(this.getSearchCriteria())){
			CommonSearchForm form = (CommonSearchForm)this.getSearchCriteria();
			if (!Utils.isNullEmpty(form.getNoStart())){
				txtNoStart.setText(form.getNoStart());
			}
			if (!Utils.isNullEmpty(form.getNoEnd())){
				txtNoEnd.setText(form.getNoEnd());
			}
			if (!Utils.isNullEmpty(form.getName())){
				txtSearchName.setText(form.getName());
			}
		}
		//
		try {
			if (!initData()) {
				lockScreen(true);
				return;
			}
		} catch (FatalException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}
	
	/**
	 * get initialize data
	 *
	 */
	@SuppressWarnings("unchecked")
	private boolean initData() throws FatalException {

		Map map = new HashMap();
		map.put(Const.SYSTEM_CONFIG.ROOM_TYPE, Boolean.TRUE);		
		map.put(Const.SYSTEM_CONFIG.ROOM_STATUS, Boolean.TRUE);
		
//		map = SWTUtils.ComboProcess.getComboInitItems(map, this);
		
		String[] items = (String[])map.get(Const.SYSTEM_CONFIG.ROOM_TYPE);
		if (items == null || items.length == 0 || Utils.isNullEmpty(items[1])){
			MsgBoxUtils.errorMsgBox("errors.COMBO_DATA_NOT_SET", 
					new Object[]{LangResources.getText("SWTRoomSearch.lblSearchType")});
			return false;
		}
		cmbType.setItems(items);
		
		//room status
		items = (String[])map.get(Const.SYSTEM_CONFIG.ROOM_STATUS);
		if (items == null || items.length == 0 || Utils.isNullEmpty(items[1])){
			MsgBoxUtils.errorMsgBox("errors.COMBO_DATA_NOT_SET", 
					new Object[]{LangResources.getText("SWTRoomSearch.lblRoomStatus")});
			return false;
		}
		cmbRoomStatus.setItems(items);
			
		return true;
	}

	/**
	 * clearAction
	 */
	protected void clearAction() {
		
		SWTUtils.OperatorUI.clearAll(this.getChildren());
		SWTUtils.OperatorUI.setEnableAll(grpSearch.getChildren(), true);
		Control[] infoGrp = new Control[]{
				tblInfo,
				btnSelect
		};
		SWTUtils.OperatorUI.setEnableAll(infoGrp, false);
		txtNoStart.setFocus();
	}

	/**
	 * displayAction
	 */
	protected void displayAction() {
		
		try {
			if (!chkInput()){
				return;
			}
			
			CommonSearchForm form = new CommonSearchForm();
			form.setActionForm("commonSearchForm");
			form.setActionMethod("getRoomList");
			
			form.setNoStart(Utils.toEmpty(txtNoStart.getText()));
			form.setNoEnd(Utils.toEmpty(txtNoEnd.getText()));
			form.setSearchName(Utils.toEmpty(txtSearchName.getText()));
			form.setRoomType(SWTUtils.ComboProcess.getSelectingValue(cmbType));
			form.setRoomStatus(SWTUtils.ComboProcess.getSelectingValue(cmbRoomStatus));
			form = (CommonSearchForm)execute(form);
			
			if (form.getList().isEmpty()){
				MsgBoxUtils.warningMsgBox("warning.NO_DATA_FOUND");
				txtNoStart.setFocus();
				return;
			}
			
			displayTable(form.getList());
			
			Control[] infoGrp = new Control[]{
					tblInfo,
					btnSelect
			};
			SWTUtils.OperatorUI.setEnableAll(infoGrp, true);
			tblInfo.setSelection(0);
			tblInfo.setFocus();
			
			String msg = Integer.toString(form.getList().size());
			msg += " " + MsgBoxUtils.getMessage("info.ROWS", new Object[]{});
			clblMessage.setText(msg);
			
		} catch (ClientException e) {
			log.error("ClientException.", e);
			fatalErrorMsgBox();
		} catch (FatalException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}

	/**
	 * check input data
	 * @return boolean
	 */
	private boolean chkInput() throws ClientException {
		
		if (!SWTUtils.Check.checkNumeric(txtNoStart, 
				LangResources.getText("SWTRoomSearch.lblSearchNo"))){
			return false;
		}
		
		if (!SWTUtils.Check.checkNumeric(txtNoEnd, 
				LangResources.getText("SWTRoomSearch.lblSearchNo"))){
			return false;
		}
		
		if (!Utils.isNullEmpty(txtNoStart.getText()) && !Utils.isNullEmpty(txtNoEnd.getText())) {
			int noS = Integer.parseInt(Utils.toNormalNumber(txtNoStart.getText()));
			int noE = Integer.parseInt(Utils.toNormalNumber(txtNoEnd.getText()));
			if (noS > noE){
				MsgBoxUtils.errorMsgBox("errors.NUMBER_GREATER_COMPARE", 
						new Object[]{LangResources.getText("SWTRoomSearch.lblSearchNo"),
									LangResources.getText("SWTRoomSearch.lblSearchNo")
									});
				txtNoStart.setFocus();
				return false;
			}
		}
		
		return true;
	}

	/**
	 * set data to table
	 * @param list
	 */
	private void displayTable(ArrayList list) {

		tblInfo.removeAll();
		
		int rowcount = TBL_ROW_COUNT;
		if (list.size() >= rowcount){
			rowcount = list.size() + 2;
		}
		for (int i = 0; i < rowcount; i++) {
			TableTreeItem parent = new TableTreeItem(tableTree, SWT.NONE);
			parent.setBackground(BaseConstant.COLOR_TABLE_ROW_EVEN);
			
			if (i < list.size()){
				MstRoomDTO room = (MstRoomDTO)list.get(i);
				
				int idx = 0;
				parent.setText(idx++, room.getRoomName());		//name
				parent.setText(idx++, room.getRoomTypeName());	//room type
				parent.setText(idx++, room.getStatusName());	//status
				parent.setText(idx++, "");						//rent type
				parent.setText(idx++, "");						//price
				parent.setText(idx++, room.getDescription());	//description
				
				parent.setData(Const.ITEMID, room);
				
				ArrayList priceList = room.getPriceList();
				String preRentTypeNo = "";
				for (int j = 0; j < priceList.size(); j++) {
					MstRoomPriceDTO price = (MstRoomPriceDTO)priceList.get(j);
					TableTreeItem child = new TableTreeItem(parent, SWT.NONE);
					
					idx = 0;
					child.setText(idx++, "");									//name
					child.setText(idx++, "");									//room type
					child.setText(idx++, "");									//status
					String rentTypeNo = price.getRentType();
					if (!rentTypeNo.equals(preRentTypeNo)){
						child.setText(idx++, price.getRentTypeName());			//rent type
					}else{
						child.setText(idx++, "");
					}
					child.setText(idx++, Utils.formatDouble(price.getPrice()) 
										+ " " + price.getMoneyTypeName());		//price
					child.setText(idx++, "");									//description
					
					preRentTypeNo = rentTypeNo;					
					child.setData(Const.ITEMID, room);
				}
				
				//Expand the parent item
				parent.setExpanded(true);
			}
		}
	}

	/**
	 * Create contents of the dialog
	 */
	protected void initialize() {
		grpSearch = new Group(this, SWT.NONE);
		grpSearch.setBounds(20, 14, 625, 117);
		grpSearch.setBackground(SWTResourceManager.getColor(234, 234, 234));

		final CLabel lblSearchNo = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblSearchNo.setFont(BaseConstant.FONT_BASE_LABEL);
		lblSearchNo.setBounds(20, 20, 100, 22);
		lblSearchNo.setText(LangResources.getText("SWTRoomSearch.lblSearchNo"));

		txtNoStart = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtNoStart.setTextLimit(3);
		txtNoStart.setFont(BaseConstant.FONT_BASE_TEXT);
		txtNoStart.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtNoStart.setBounds(125, 20, 120, 22);

		final Label lbl1 = new Label(grpSearch, SWT.CENTER);
		lbl1.setFont(BaseConstant.FONT_BASE_LABEL);
		lbl1.setBackground(BaseConstant.COLOR_BGR_BASE);
		lbl1.setBounds(251, 24, 22, 18);
		lbl1.setText("-");

		txtNoEnd = new Text(grpSearch, SWT.BORDER | SWT.RIGHT);
		txtNoEnd.setTextLimit(3);
		txtNoEnd.setTabs(2);
		txtNoEnd.setFont(BaseConstant.FONT_BASE_TEXT);
		txtNoEnd.setBackground(BaseConstant.COLOR_TEXT_NORMAL);
		txtNoEnd.setBounds(279, 20, 120, 22); 

		final CLabel lblSearchName = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblSearchName.setBounds(20, 48, 100, 22);
		lblSearchName.setFont(BaseConstant.FONT_BASE_LABEL);
		lblSearchName.setText(LangResources.getText("SWTRoomSearch.lblSearchName"));

		txtSearchName = new Text(grpSearch, SWT.BORDER);
		txtSearchName.setBounds(125, 48, 380, 22);
		txtSearchName.setTextLimit(30);
		txtSearchName.setTabs(3);
		txtSearchName.setFont(BaseConstant.FONT_BASE_TEXT);
		txtSearchName.setBackground(BaseConstant.COLOR_TEXT_NORMAL);

		final CLabel lblSearchType = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblSearchType.setBounds(20, 76, 100, 22);
		lblSearchType.setFont(BaseConstant.FONT_BASE_LABEL);
		lblSearchType.setText(LangResources.getText("SWTRoomSearch.lblSearchType"));

		cmbType = new Combo(grpSearch, SWT.READ_ONLY);
		cmbType.setBounds(125, 74, 120, 24);
		cmbType.setTextLimit(200);
		cmbType.setFont(BaseConstant.FONT_BASE_TEXT);
		
		final CLabel lblRoomStatus = new CLabel(grpSearch, SWT.CENTER | SWT.BORDER);
		lblRoomStatus.setBounds(279, 76, 100, 22);
		lblRoomStatus.setFont(BaseConstant.FONT_BASE_LABEL);
		lblRoomStatus.setText(LangResources.getText("SWTRoomSearch.lblRoomStatus"));

		cmbRoomStatus = new Combo(grpSearch, SWT.READ_ONLY);
		cmbRoomStatus.setBounds(385, 76, 120, 24);
		cmbRoomStatus.setTextLimit(200);
		cmbRoomStatus.setFont(BaseConstant.FONT_BASE_TEXT);		

		btnSearch = new Button(grpSearch, SWT.NONE);
		btnSearch.setBounds(511, 75, 100, 23);
		btnSearch.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));
		btnSearch.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnSearch.setText(LangResources.getText("btnSearch"));
		btnSearch.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnSearch.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				displayAction();
			}
		});
		
		setDefaultButton(btnSearch);

		final Label line1 = new Label(this, SWT.HORIZONTAL | SWT.SEPARATOR);
		line1.setBounds(0, 137, 670, 15);
		line1.setBackground(BaseConstant.COLOR_BGR_BASE);
		
		tableTree = new TableTree(this, SWT.FULL_SELECTION | SWT.BORDER);
		tableTree.setBounds(20, 158, 625, 307);
		tableTree.setFont(BaseConstant.FONT_BASE_LABEL);
		
		tblInfo = tableTree.getTable();
		tblInfo.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(final SelectionEvent arg0) {
				selectAction();
			}
		});
		tblInfo.setData(BaseConstant.TABLE_ROW_COUNT, Integer.toString(TBL_ROW_COUNT));
		tblInfo.setLinesVisible(true);
		tblInfo.setHeaderVisible(true);
		
		final TableColumn tcolRoomName = new TableColumn(tblInfo, SWT.NONE);
		tcolRoomName.setAlignment(SWT.RIGHT);
		tcolRoomName.setWidth(120);
		tcolRoomName.setText(LangResources.getText("SWTRoomSearch.tblInfo.tcolRoomName"));
		
		final TableColumn tcolType = new TableColumn(tblInfo, SWT.NONE);
		tcolType.setWidth(70);
		tcolType.setText(LangResources.getText("SWTRoomSearch.tblInfo.tcolType"));
		
		final TableColumn tcolUnit = new TableColumn(tblInfo, SWT.NONE);
		tcolUnit.setWidth(80);
		tcolUnit.setText(LangResources.getText("SWTRoomSearch.tblInfo.tcolStatus"));

		final TableColumn tcolRentType = new TableColumn(tblInfo, SWT.NONE);
		tcolRentType.setWidth(80);
		
		final TableColumn tcolPrice = new TableColumn(tblInfo, SWT.RIGHT);
		tcolPrice.setWidth(90);
		tcolPrice.setText(LangResources.getText("SWTRoomSearch.tblInfo.tcolPrice"));
		
		final TableColumn tcolDescription = new TableColumn(tblInfo, SWT.NONE);
		tcolDescription.setWidth(160);
		tcolDescription.setText(LangResources.getText("SWTRoomSearch.tblInfo.tcolDescription"));

		final Label line2 = new Label(this, SWT.HORIZONTAL | SWT.SEPARATOR);
		line2.setBounds(0, 500, 670, 15);
		line2.setBackground(BaseConstant.COLOR_BGR_BASE);
		
		clblMessage = new CLabel(this, SWT.RIGHT | SWT.SHADOW_IN | SWT.BORDER);
		clblMessage.setAlignment(SWT.CENTER);
		clblMessage.setForeground(BaseConstant.COLOR_LINK_LABEL);
		clblMessage.setBounds(15, 520, 250, 25);
		clblMessage.setFont(BaseConstant.FONT_BOLD_LABEL);
		clblMessage.setBackground(BaseConstant.COLOR_BGR_LABEL);
		
		btnSelect = new Button(this, SWT.NONE);
		btnSelect.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnSelect.setBounds(545, 471, 100, 23);
		btnSelect.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnSelect.setText(LangResources.getText("btnSelect"));
		btnSelect.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnSelect.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				selectAction();
			}
		});

		btnClear = new Button(this, SWT.NONE);
		btnClear.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnClear.setBounds(439, 522, 100, 23);
		btnClear.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnClear.setText(LangResources.getText("btnClear"));
		btnClear.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnClear.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				clearAction();
			}
		});
		
		btnClose = new Button(this, SWT.NONE);
		btnClose.addFocusListener(new FocusAdapter() {
			public void focusGained(final FocusEvent arg0) {
				clblMessage.setText("");
			}
		});
		btnClose.setBounds(545, 522, 100, 23);
		btnClose.setFont(BaseConstant.FONT_BASE_BUTTON);
		btnClose.setText(LangResources.getText("btnClose"));
		btnClose.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		btnClose.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (!closeAction(true)) {
					btnClose.setFocus();
				}
			}
		});
	}

	/**
	 * select action
	 *
	 */
	protected void selectAction() {

		try {
			TableTreeItem item = tableTree.getSelection()[0];
			MstRoomDTO room = (MstRoomDTO)item.getData(Const.ITEMID);
			if (null == room){
				MsgBoxUtils.errorMsgBox("errors.NOT_SELECTED_RECORD");
				btnSelect.setFocus();
				return;
			}
			
			setResult(room);
			
			this.closeAction(false);
			
		} catch (ClientException e) {
			log.error("FatalException.", e);
			fatalErrorMsgBox();
		}
	}
}
